<template>
<u--form
	class="page1"
	labelPosition="left"
	labelWidth="80"
	:model="form"
	:rules="rules"
	ref="uForm"
	@tap="showHzs = false"
>
	<u-form-item
		label="选择汉服"
		borderBottom
	>
		<view class="centerText" @click="show = true">请选择</view>
	</u-form-item>
	<u-form-item
		label="汉服名称"
		prop="hanfuName"
		borderBottom
		required
	>
		<u--input v-model="form.hanfuName" placeholder="汉服的名称信息等"></u--input>
	</u-form-item>
	<u-form-item
		label="租售类型"
		borderBottom
	>
		<u-radio-group v-model="form.type" placement="row" @change="typeChange">
			<u-radio v-for="item in orderType" :label="`${item.name}`" :name="item.id" class="mar16"></u-radio>
		</u-radio-group>
	</u-form-item>
	<u-button v-if="form.type===2" plain type="primary" text="带妆售卖" @click="showHzsArea = !showHzsArea"></u-button>
	<!-- 团购计算器 -->
	<u-button v-if="form.type===1" plain type="primary" text="团购计算器" @click="showCounter = !showCounter"></u-button>
	<view class="counterView" v-if="form.type===1&&showCounter">
		<u-radio-group v-model="counter.type" placement="row" shape="square" class="groupPlatformBar">
			<u-radio v-for="item in groupPlatform" :label="item.name" :name="item.id" class="mar16"></u-radio>
		</u-radio-group>
		<u-form-item label="原价格" borderBottom>
			<u--input v-model="counter.originPrice" type="digit" placeholder="在店内的实际租赁价格" clearable></u--input>
		</u-form-item>
		<u-form-item label="团购价格" borderBottom>
			<u--input v-model="counter.groupPrice" type="digit" placeholder="在团购平台上(如抖音等)的租赁价格" clearable></u--input>
		</u-form-item>
		<view class="tips">*例子：店内租赁价129的衣服，客户下单了一个30的斗篷，可以填写原价格129、团购价格30，平时原价格和团购价格填写一致即可</view>
	</view>
	<u-form-item
		label="价格"
		prop="price"
		borderBottom
		required
	>
		<u--input v-model="form.price" type="digit" clearable></u--input>
	</u-form-item>
	<template v-if="[1,3].indexOf(form.type)>-1 || showHzsArea">
		<u-form-item
			:label="roleName"
			prop="makeupArtist"
			borderBottom
		>
			<view class="inputBox">
				<u--input 
					v-model="form.makeupArtist" 
					:placeholder="`请输入${roleName}的名字`" 
					class="hzsIpt"
					@focus="showHzs = true"
				></u--input>
				<view class="cosmetician" v-if="showHzs&&roleList.length>0">
					<view class="fcc-sb item u-border-bottom" v-for="(item, i) in roleList" :key="i" @click="slectHzs(item)">
						<text>{{item}}</text>
						<view class="rightIcon" @click.stop="order.deleteCosmetician(i, form.type)">
							<u-icon name="close-circle-fill" size="40rpx" color="#999"></u-icon>
						</view>
					</view>
				</view>
			</view>
		</u-form-item>
		<u-form-item
			label="提成"
			prop="makeupFees"
			borderBottom
		>
			<u--input v-model="form.makeupFees" type="number" :placeholder="`${roleName}提成费用`"></u--input>
		</u-form-item>
	</template>
	<u-form-item
		label="备注"
		prop="remark"
		borderBottom
	>
		<u--textarea v-model="form.remark" placeholder="请输入备注内容"></u--textarea>
	</u-form-item>
	<u-button @click="submit" type="primary">提交</u-button>
</u--form>
<u-picker 
	:defaultIndex="defaultIndex"
	v-if="show"
	:show="show" 
	:columns="columns" 
	visibleItemCount="8"
	keyName="name" 
	@confirm="cfmHandle"
	@cancel="show = false"
	@change="changeHandler"
></u-picker>
</template>

<script setup>
import { onLoad, onUnload } from '@dcloudio/uni-app'
import { useOrderStore, useGoodsStore } from '@/stores'
import { dynasty, orderType, numFilter } from '@/utils/data'
import { groupBy } from 'lodash-es'

const order = useOrderStore()
const goods = useGoodsStore()
const uForm = ref() 
const show = ref(false) // 汉服选择picker
const showHzs = ref(false)
const showHzsArea = ref(false)
const defaultIndex = ref([0, 0])
const showCounter = ref(false)
const counter = reactive({
	type: 1, // 团购平台类型
	originPrice: '',
	groupPrice: '',
})
const groupPlatform = [
	{id: 1, name: '抖音 ', rate: 0.95},
	{id: 2, name: '美团', rate: 0.92},
]
watch(counter, (n,o)=>{
	if(n.originPrice&&n.groupPrice){
		const groupPrice = Number(n.groupPrice)
		const findObj = groupPlatform.find(item=>item.id==counter.type)
		// const price = Number(n.originPrice)-groupPrice+(groupPrice/100*95)
		const price = Number(n.originPrice)-groupPrice+(groupPrice*findObj.rate)
		form.price = numFilter(price)
	}
})
let selectHanFu = null

const form = reactive({
	// selectHanfuId: null,
	hanfuName: '', // 汉服衣服的名字
	type: 1,
	price: '', // 订单价格
	makeupArtist: '', // 化妆师
	makeupFees: '', // 妆造费用
	remark: '',
	leaseStatus: 0, // 0 归还  1 租赁中
})
const rules = reactive({
	hanfuName: [
		{
			required: true,
			message: '请输入汉服的名称',
			trigger: ['blur', 'change']
		}
	],
	// price: [
	// 	{
	// 		required: true,
	// 		message: '请输入价格',
	// 		trigger: ['blur', 'change']
	// 	},
	// ]
})
const columns = reactive([dynasty, []])
const roleName = computed(()=>form.type===3?'摄影师':'化妆师')
const roleList = computed(()=>form.type===3?order.cameramanList:order.cosmeticianList)
let columnData = {}

function typeChange(type){
	if(selectHanFu){
		if(form.type===1){
			form.price = selectHanFu.rentalPrice
		}else if(form.type===2){
			form.price = selectHanFu.buyPrice
		}else{
			form.price = ''
		}
	}
}

function changeHandler(e){
	const { columnIndex, value, values, index, picker } = e;
	if (columnIndex === 0) {
		const arr = columnData[value[0].id] ? columnData[value[0].id] : []
	    picker.setColumnValues(1, arr);
	}
}

function cfmHandle({indexs, value}){
	show.value = false
	const { name, buyPrice, rentalPrice, imgUrl, dynasty, timestamp } = value[1]
	selectHanFu = {imgUrl, dynasty, goodsId: timestamp, rentalPrice, buyPrice}
	form.hanfuName = name
	typeChange()
	const goodsIndex = columns[1].findIndex(item=>item.timestamp === timestamp)
	defaultIndex.value = [indexs[0], goodsIndex]
}

function slectHzs(hzs){
	form.makeupArtist = hzs
	showHzs.value = false
}

function submit() {
	if(!form.price) return uni.$u.toast('订单的价格还未填写')
	uForm.value.validate().then(res => {
		let msg;
		const data = { ...form }
		if(selectHanFu){
			data.imgUrl = selectHanFu.imgUrl
			data.dynasty = selectHanFu.dynasty
			data.goodsId = selectHanFu.goodsId
			// 如果是售卖类型更新汉服库汉服的状态为已售卖
			goods.modifyGoodsState(selectHanFu.goodsId, form.type===2 ? 1 : 0)
		}
		if(form.timestamp){
			msg = '编辑'
			// 更新商品数据
			const tmp = (selectHanFu && form.goodsId===selectHanFu.goodsId) ? form : data
			order.editOrder(tmp)
		}else{
			msg = '添加'
			order.addOrder({ ...data, leaseStatus: 1, timestamp: Date.now() })
		}
		uni.showToast({icon: 'success', title: `${msg}成功`, duration: 2000, complete(){
			setTimeout(uni.navigateBack, 2000)
			if(form.makeupArtist) order.addCosmetician(form.makeupArtist, form.type); // 添加化妆师
		}})
		// 售卖类型的订单可能还要删除汉服goods
	}).catch(errors => {
		// uni.$u.toast('校验失败')
	})
}
onLoad((option)=>{
	// 先过滤
	const available_list = goods.list.filter(item=>!Boolean(item.state))
	// 再分组
	columnData = groupBy(available_list, 'dynasty')
	columns[1] = columnData[dynasty[0].id] ? columnData[dynasty[0].id] : []
	// 编辑的时候先获取数据 然后填充表单
	if(option&&option.order){
		uni.setNavigationBarTitle({title: "编辑订单信息"})
		const data = JSON.parse(option.order)
		for(let key in data){
			form[key] = data[key]
		}
		// 映射picker选中的数据
		for(let key in columnData){
			const arr = columnData[key]
			if(arr.length>0){
				const index = arr.findIndex(item=>form.goodsId===item.timestamp)
				if(index>-1){
					const {imgUrl, dynasty: did, timestamp, rentalPrice, buyPrice} = arr[index]
					selectHanFu = {imgUrl, dynasty: did, goodsId: timestamp, rentalPrice, buyPrice}
					// 设置默认选中数据
					columns[1] = arr
					defaultIndex.value[0] = dynasty.findIndex(item=>item.id===did);
					defaultIndex.value[1] = index
					break;
				}
			}
		}
	}
})
onUnload(()=>{
	// 清空数据
	selectHanFu = null;
})
</script>

<style lang="scss" scoped>
	.page1{
		padding-bottom: 40rpx;
	}
	.groupPlatformBar{
		padding: 20rpx 0 10rpx;
	}
	.mar16{
		margin-right: 30rpx;
	}
	.centerText{
		width: 100%;
		height: 60rpx;
		line-height: 60rpx;
		text-align: center;
	}
	.counterView{
		// background-color: #ddd;
		// border: 2rpx solid #ccc;
		margin: 0 -20rpx;
		padding: 0 20rpx;
		.tips{
			color: red;
			font-size: 24rpx;
		}
	}
	.inputBox{
		width: 100%;
		position: relative;
		.hzsIpt{
			height: 80rpx;
		}
		.cosmetician{
			position: absolute;
			width: 100%;
			top: 80rpx;
			left: 0;
			background-color: #fff;
			box-shadow: 0 0 10rpx #ccc;
			z-index: 2;
			max-height: 700rpx;
			overflow-y: auto;
			.item{
				width: 100%;
				height: 80rpx;
				padding: 0 20rpx;
				&:last-child{
					border: 0!important;
				}
			}
			.rightIcon{
				width: 100rpx;
				height: 80rpx;
				display: flex;
				justify-content: flex-end;
				align-items: center;
			}
		}
	}
</style>